<?php
// Enter the path that the oauth library is in relation to the php file
// This is required for Yelp authentication.
require_once ('../php/place.php');
require_once ('../php/util.php');
require_once ('../php/facebook_api_handler.php');
require_once ('../php/yelp_api_handler.php');
require_once ('../php/citygrid_search_api_handler.php');

// Combined results from Facebook, Yelp and CityGrid.
$combinedResults = array();

//Facebook
$facebook = new FacebookApiHandler();
$facebook->connect();
$facebook_response = $facebook->response;

if (!is_null($facebook_response)) {
    foreach ($facebook_response as $finding) {
        $place = new Place();
        $place->name = $finding["name"];
        $place->facebook_page_id = $finding["page_id"];
        array_push($combinedResults, $place);
    }
} else {
    echo "You have no friends who like restaurants.";
}

//Yelp
$term = "sushi";
$location = "River%20Ridge,LA";
$yelp = new YelpAPIHandler($term, $location);
$yelp->connect();
$yelp_response = $yelp->response;

if (!is_null($yelp_response)) {
    foreach ($yelp_response->businesses as $business) {
        $place = new Place();
        $place->name = $business->name;
        $place->rating = $business->rating;
        $place->url = $business->url;
        $place->yelp_id = $business->id;
        array_push($combinedResults, $place);
    }
}

// CityGrid
$citygrid = new CityGridSearchAPIHandler($term, $location);
$citygrid->connect();
$citygrid_response = $citygrid->response;
$results = $citygrid_response->results;

if (!is_null($results)) {
    foreach ($results->locations as $location) {
        $place = new Place();
        $place->name = $location->name;
        $place->rating = $location->rating / 2;
        $place->url = $location->website;
        $place->citygrid_id = $location->public_id;
        array_push($combinedResults, $place);
    }
}

//sort results alphabetically by __toString method.
asort($combinedResults);

printf("<table class='mystyle'>");
printf("<tr style='font-weight:bold'>");
printf("<td>Name</td><td>Rating</td><td>Yelp ID</td><td>CityGrid ID</td><td>Facebook Page ID");
$cleanedResults = combineDuplicatePlaces($combinedResults);
foreach ($cleanedResults as $result) {
    printf("<tr>");
    printf("<td>");
    print is_null($result->url) ? $result->name : "<a href='" . $result->url . "'>" . $result->name . "</a>";
    printf("</td>");
    printf("<td>");
    print $result->rating ;
    printf("</td>");
    printf("<td>");
    print $result->yelp_id ;
    printf("</td>");
    printf("<td>");
    print $result->citygrid_id ;
    printf("</td>");
    printf("<td>");
    print $result->facebook_page_id ;
    printf("</td>");
    printf("</tr>");
}
printf("</table>");

?>
